<script lang="ts" setup>
  import * as qiniu from "qiniu-js";
  import { v4 as uuidv4 } from "uuid";
  import { request } from "@/api/request";
  import { onMounted, ref } from "vue";
  import * as _ from "@usemath/utils";
  import { useDictStore } from "@/stores";

  export type UploadFile = {
    id: number;
    name: string;
    url: string;
    originalName: string;
  };

  const dictStore = useDictStore();
  const emits = defineEmits<{
    (e: "change", files: UploadFile[]): void;
  }>();
  const files = ref<UploadFile[]>([]);
  const props = defineProps<{
    defaultFileList?: any[];
    baseURL?: string;
  }>();

  onMounted(async () => {});

  const customRequest = async (option: any) => {
    const { fileItem } = option;
    const fileType = dictStore.value("fileType", fileItem.file.type);
    const observer = {
      async complete(result: any) {
        const { key, hash } = result;
        const response = await request("/admin/file/create", {
          name: fileItem.name,
          url: props.baseURL + "/" + key,
          typeValue: fileType.value,
          hash: hash,
        });

        if (response.code === 20000) {
          files.value.push({
            id: response.data.id,
            name: response.data.name,
            url: response.data.url,
            originalName: fileItem.name,
          });
          emits("change", files.value);
        }
      },
    };

    let qiniuToken = _.getStorage<string>("qiniuToken") || "";
    if (qiniuToken === "") {
      const response = await request("/admin/file/getQiniuToken");
      if (response.code === 20000 && response.data) {
        qiniuToken = response.data;
        _.setStorage("qiniuToken", qiniuToken, 1800);
      }
    }

    const observable = qiniu.upload(fileItem.file, uuidv4() + "." + fileType.value, qiniuToken);

    const subscription = observable.subscribe(observer);

    return {
      abort() {
        subscription.unsubscribe();
      },
    };
  };
</script>

<template>
  <a-upload :custom-request="customRequest" :default-file-list="defaultFileList" :show-file-list="false">
    <template #upload-button v-if="$slots.default">
      <slot></slot>
    </template>
  </a-upload>
</template>
